package com.itita.ww2.handler.requesthandler.mission;

import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.data.WorldMapConfig;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.area.AreaDefault;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.model.user.battle.BaseBattleState.BattleType;
import com.itita.ww2.utils.handler.IRequestOper;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;

/**
 * 副本开始
 * @author NorthLan
 *
 */
public class MissionStart implements IRequestOper {
	private static final Logger logger = LoggerFactory.getLogger(MissionStart.class);

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		UserProfile userProfile = UserService.getInstance().getUserProfile(user);
		int blockId = params.getInt("blockId");
		int cityId = params.getInt("cityId");
		ISFSObject army = params.getSFSObject("army");
		String missionId = WorldMapConfig.getCityMissionId(blockId, cityId);

		if (userProfile.getBattleManager().getBattleState(BattleType.Mission) != null) {
			MessageHandler.getInstance().sendMsg(requestCMD, null, user, null, true);
		}

		// 没解锁区块就来打副本?
		if (!userProfile.getWMManager().getUserUnlockDataMgr().isBlockUnlocked(blockId)) {
			throw new WW2Exception(); // invalid-opt
		}

		if (!userProfile.getUserInfo().isFatigueEnough(missionId)) {
			throw new WW2Exception(WW2ExceptionCode.USER_FATIGUE_NOT_ENOUGH);
		}

		// 战斗+
		userProfile.getBattleManager().enterBattle(BattleType.Mission, army, blockId, cityId, missionId);

		// 暂时 退出map区域
		userProfile.setCurArea(new AreaDefault());

		MessageHandler.getInstance().sendMsg(requestCMD, null, user, null, true);

		logger.info("[User:{} | {} | start mission {}|", userProfile.getNickname(), userProfile.getUid(), missionId);
		return true;
	}

}
